package org.ricks.common.db;


import org.ricks.actor.ActorRunnable;
import org.ricks.db.DbOperationEnum;
import org.ricks.db.TableValueBuilder;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author chenwei
 * @Title:
 * @Package
 * @Description:
 * @date 2020/12/3017:39
 */
public class RepositoryDao<T,K> extends BaseDao<T>{

    public RepositoryDao() {
    }

    public RepositoryDao(Class clazz) {
        super(clazz);
    }

    public RepositoryDao(Class clazz,int split) {
        super(clazz,split);
    }


    public void save(T... objects) {
        try {
            if (objects.length > 1) {
                Object[][] args = new Object[objects.length][tableMeta.getColumns().size()];
                for (int i = 0; i < objects.length; i++) {
                    args[i] = TableValueBuilder.listInsertValue(tableMeta, objects[i]);
                }
                batch(true, insertSql, args);
            } else {
                Object[] args = TableValueBuilder.listInsertValue(tableMeta, objects[0]);
                update(true, insertSql, args);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void delete(T... objects) {
        try {
            Object[][] args = new Object[objects.length][1];
            for (int i = 0; i < objects.length; i++) {
                args[i][0] = TableValueBuilder.getPrimaryKeyValue(tableMeta, objects[i]);
            }
            if (objects.length > 1) {
                batch(true, deleteSql, args);
            } else {
                delete( TableValueBuilder.getPrimaryKeyValue(tableMeta, objects[0]));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void update(T... objects) {
        try {
            Object[][] args = new Object[objects.length][tableMeta.getColumns().size()];
            for (int i = 0; i < objects.length; i++) {
                args[i] = TableValueBuilder.listUpdateValue(tableMeta, objects[i]);
            }
            batch(true,updateSql, args);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
